package com.sky.job;

import com.alibaba.fastjson.JSON;
import com.hxc.pay.CommonPayTemplate;
import com.sky.mapper.user.UserOrderMapper;
import com.sky.pojo.Orders;
import com.sky.service.UserService.PaySuccessService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Component
@Slf4j public class OderJob {
    @Autowired
    UserOrderMapper orderMapper;
    @Autowired
    CommonPayTemplate commonPayTemplate;
    @Resource
    PaySuccessService paySuccessService;

    /**
     * 客户超时间未支付就更改订单状态
     */
 //   @Scheduled(cron = "0/5 * * * * ?")
    public void scanCancelOder() {
        log.warn("-----扫描15分之前未支付的订单");
        // 15分钟没有支付就是超时 进行扫描
        //15分钟前的时间
        LocalDateTime time = LocalDateTime.now().minusSeconds(15 * 60);
        List<Orders> ordersList = orderMapper.selectBySatus(Orders.PENDING_PAYMENT, time);
        if (!CollectionUtils.isEmpty(ordersList)) {
            ordersList.forEach(orders -> {
                String json = commonPayTemplate.queryOrder(orders.getNumber());
                Map<String, String> resultJson = JSON.parseObject(json, Map.class);
                boolean tradeState = "NOTPAY".equals(resultJson.get("trade_state").toString());
                // 未支付
                if (tradeState) {
                    //调用关单接口
                    commonPayTemplate.close(orders.getNumber());
                    //修改数据库的订单支付状态
                    Orders os = new Orders();
                    os.setStatus(Orders.CANCELLED_ORDER);
                    os.setCancelTime(LocalDateTime.now());
                    os.setCancelReason("订单超时未支付");
                    os.setNumber(orders.getNumber());
                    int i = orderMapper.updateOutTradeNo(os);
                    log.warn("订单定时任务修改后的信息：{}", i);

                }
            });
        }
    }
    /**
     * 已经支付过了 但是微信的通知失败了 需要主动向微信发送查单 并且修改状态
     */
  //  @Scheduled(cron = "0/3 * * * * *")
    public void queryOrderTask(){
//        1.查询当下未支付的订单
        System.out.println("----扫描15分钟内未支付,且微信通知失败的订单---");
        LocalDateTime maxTime = LocalDateTime.now().minusSeconds(15 * 60);
        List<Orders> ordersList = orderMapper.selectOrdersByStatusAndTime(Orders.PENDING_PAYMENT,maxTime, null);
        if (ordersList!=null&&ordersList.size()>0){
            ordersList.forEach(orders -> {
                //        2.调用微信的查询接口，查询订单的支付状态
                String jsonStr = commonPayTemplate.queryOrder(orders.getNumber());
                String trade_state = JSON.parseObject(jsonStr, Map.class).get("trade_state").toString();
                if("SUCCESS".equals(trade_state)){
                    // 3.如果是已支付，修改订单状态未已支付
                    orders.setStatus(Orders.TO_BE_CONFIRMED);
                    orders.setCheckoutTime(LocalDateTime.now());
                    orders.setPayStatus(Orders.PAID);
                    paySuccessService.success(orders.getNumber());
                }
            });
        }
    }
}
